package com.woniuxy.vuecli.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.vuecli.entity.Employee;
import com.woniuxy.vuecli.entity.PageBean;
import com.woniuxy.vuecli.exception.EmailUsedException;
import com.woniuxy.vuecli.exception.EnameNotExistsException;
import com.woniuxy.vuecli.exception.PasswordWrongException;
import com.woniuxy.vuecli.mapper.EmployeeMapper;
import com.woniuxy.vuecli.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

/**
 * @Author author
 * @Create 2024-01-15 16:09
 */
//IoC:<bean id="" class="" />
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    EmployeeMapper employeeMapper;


    @Override
    public PageBean<Employee> getAll(int pageIndex, int pageSize, Employee employee) {
        PageHelper.startPage(pageIndex, pageSize);
        List<Employee> employees = employeeMapper.getAll(employee);
        PageInfo<Employee> pageInfo=new PageInfo<>(employees);
        PageBean<Employee> pageBean=new PageBean<>();
        pageBean.setBeanList(pageInfo.getList());
        pageBean.setTotalPage(pageInfo.getPages());
        pageBean.setPageSize(pageSize);
        pageBean.setPageIndex(pageIndex);
        pageBean.setTotalRecord((int) pageInfo.getTotal());
        return pageBean;
    }

    @Override
    public boolean emailUsed(String email) {
        //邮箱被使用，true
        return employeeMapper.getByEmail(email)!=null;
    }

    @Override
    public void add(Employee employee) {
        //检查邮箱是否被使用的后端验证
        if(emailUsed(employee.getEmail())){
            //邮箱被使用，抛异常
            throw new EmailUsedException("邮箱被使用");
        }
        employee.setPassword(DigestUtils.md5DigestAsHex("aaa".getBytes()));
        employeeMapper.insertEmployee(employee);
    }

    @Override
    public Employee login(String ename, String password) {
        //查询，比较用户名，密码
        Employee employee = employeeMapper.getByEname(ename);
        if(employee==null){
            //用户名不存在
            throw new EnameNotExistsException("用户名不存在");
        }
        if(!employee.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))){
            throw new PasswordWrongException("密码错误");
        }
        return employee;
    }
}
